import service from './service'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useApplicationStoreWithOut } from '@/store/modules/application'

const userStore = useUserStoreWithOut()
const applicationStore = useApplicationStoreWithOut()

const request = (option: AxiosConfig) => {
    const {url, method, params, data, responseType} = option

    const headers = option.headers || {}

    if(userStore.token){
        headers['Authorization'] = 'Bearer ' +  userStore.token
    }
    if(applicationStore.code) {
        headers['x-application-code'] = applicationStore.code
    }

    return service.request({
        url: url,
        method,
        params,
        data: data,
        responseType: responseType,
        headers: {
            'Content-Type': headers?.['Content-Type'] || 'application/json',
            ...headers
        }
    })
}

export default {
    get: <T = any>(option: AxiosConfig): Promise<T> => {
        return request({method: 'get', ...option}) as Promise<T>
    },
    post: <T = any>(option: AxiosConfig): Promise<T> => {
        return request({method: 'post', ...option}) as Promise<T>
    },
    delete: <T = any>(option: AxiosConfig): Promise<T> => {
        return request({method: 'delete', ...option}) as Promise<T>
    },
    put: <T = any>(option: AxiosConfig): Promise<T> => {
        return request({method: 'put', ...option}) as Promise<T>
    },
    cancelRequest: (url: string | string[]) => {
        service.cancelRequest(url)
    },
    cancelAllRequest: () => {
       service.cancelAllRequest()
    }
}